package com.jiufengxinxi.ts.common.utils;

import java.math.BigInteger;

public class HexUtil {
	
	private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', 
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

	public static String binaryString2hexString(String bString) {
		bString = bString.toLowerCase();
		if (bString == null || bString.equals("") || bString.length() % 8 != 0)
			return null;
		StringBuffer tmp = new StringBuffer();
		int iTmp = 0;
		for (int i = 0; i < bString.length(); i += 4) {
			iTmp = 0;
			for (int j = 0; j < 4; j++) {
				iTmp += Integer.parseInt(bString.substring(i + j, i + j + 1)) << (4 - j - 1);
			}
			tmp.append(Integer.toHexString(iTmp));
		}
		return tmp.toString();
	}

	public static String hexString2binaryString(String hexString) {
		hexString = hexString.toLowerCase();
		if (hexString == null || hexString.length() % 2 != 0)
			return null;
		String bString = "", tmp;
		for (int i = 0; i < hexString.length(); i++) {
			tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16));
			bString += tmp.substring(tmp.length() - 4);
		}
		return bString;
	}

	public static String decimalToHex(int decimal) {
		String hex = "";
		while (decimal != 0) {
			int hexValue = decimal % 16;
			hex = toHexChar(hexValue) + hex;
			decimal = decimal / 16;
		}
		return hex;
	}

	// 将0~15的十进制数转换成0~F的十六进制数
	public static char toHexChar(int hexValue) {
		if (hexValue <= 9 && hexValue >= 0)
			return (char) (hexValue + '0');
		else
			return (char) (hexValue - 10 + 'A');
	}

	public static void binaryToDecimal(int n) {
		int t = 0; // 用来记录位数
		int bin = 0; // 用来记录最后的二进制数
		int r = 0; // 用来存储余数
		while (n != 0) {
			r = n % 2;
			n = n / 2;
			bin = (int) (r * Math.pow(10, t));
			t++;
		}
		System.out.println(bin);
	}

	/**
	 * 字符串转换成十六进制字符串
	 */
	public static String str2HexStr(String str) {
		StringBuilder sb = new StringBuilder("");
		byte[] bs = str.getBytes();
		int bit;
		for (int i = 0; i < bs.length; i++) {
			bit = (bs[i] & 0x0f0) >> 4;
			sb.append(HEX_CHAR[bit]);
			bit = bs[i] & 0x0f;
			sb.append(HEX_CHAR[bit]);
		}
		return sb.toString();
	}


	/**
	 * 把16进制字符串转换成字节数组
	 * 
	 * @param hexString
	 * @return byte[]
	 */
	public static byte[] hexStringToByte(String hex) {
		int len = (hex.length() / 2);
		byte[] result = new byte[len];
		char[] achar = hex.toLowerCase().toCharArray();
		for (int i = 0; i < len; i++) {
			int pos = i * 2;
			result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
		}
		return result;
	}

	private static int toByte(char c) {
		byte b = (byte) "0123456789ABCDEF".indexOf(c);
		return b;
	}


	/**
	 * 数组转换成十六进制字符串
	 * 
	 * @param byte[]
	 * @return HexString
	 */
	public static final String bytesToHexString(byte[] bArray) {
		StringBuffer sb = new StringBuffer(bArray.length);
		String sTemp;
		for (int i = 0; i < bArray.length; i++) {
			sTemp = Integer.toHexString(0xFF & bArray[i]);
			if (sTemp.length() < 2)
				sb.append(0);
			sb.append(sTemp.toUpperCase());
		}
		return sb.toString();
	}


	/**
     * 方法一：
     * byte[] to hex string
     * 
     * @param bytes
     * @return
     */
    public static String bytesToHexFun1(byte[] bytes) {
        // 一个byte为8位，可用两个十六进制位标识
        char[] buf = new char[bytes.length * 2];
        int a = 0;
        int index = 0;
        for(byte b : bytes) { // 使用除与取余进行转换
            if(b < 0) {
                a = 256 + b;
            } else {
                a = b;
            }

            buf[index++] = HEX_CHAR[a / 16];
            buf[index++] = HEX_CHAR[a % 16];
        }

        return new String(buf);
    }

    /**
     * 方法二：
     * byte[] to hex string
     * 
     * @param bytes
     * @return
     */
    public static String bytesToHexFun2(byte[] bytes) {
        char[] buf = new char[bytes.length * 2];
        int index = 0;
        for(byte b : bytes) { // 利用位运算进行转换，可以看作方法一的变种
            buf[index++] = HEX_CHAR[b >>> 4 & 0xf];
            buf[index++] = HEX_CHAR[b & 0xf];
        }

        return new String(buf);
    }

    /**
     * 方法三：
     * byte[] to hex string
     * 
     * @param bytes
     * @return
     */
    public static String bytesToHexFun3(byte[] bytes) {
        StringBuilder buf = new StringBuilder(bytes.length * 2);
        for(byte b : bytes) { // 使用String的format方法进行转换
            buf.append(String.format("%02x", new Integer(b & 0xff)));
        }

        return buf.toString();
    }

    /**
     * 将16进制字符串转换为byte[]
     * 
     * @param str
     * @return
     */
    public static byte[] toBytes(String str) {
    		str = str.toLowerCase();
        if(str == null || str.trim().equals("")) {
            return new byte[0];
        }

        byte[] bytes = new byte[str.length() / 2];
        for(int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }

        return bytes;
    }
    
    protected static char[] encodeHex(byte[] data) {
        int l = data.length;
        char[] out = new char[l << 1];
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = HEX_CHAR[(0xF0 & data[i]) >>> 4];
            out[j++] = HEX_CHAR[0x0F & data[i]];
        }
        return out;
    }

    protected static byte[] decodeHex(char[] data) {
        int len = data.length;
        if ((len & 0x01) != 0) {
            throw new RuntimeException("字符个数应该为偶数");
        }
        byte[] out = new byte[len >> 1];
        for (int i = 0, j = 0; j < len; i++) {
            int f = toDigit(data[j], j) << 4;
            j++;
            f |= toDigit(data[j], j);
            j++;
            out[i] = (byte) (f & 0xFF);
        }
        return out;
    }

    protected static int toDigit(char ch, int index) {
        int digit = Character.digit(ch, 16);
        if (digit == -1) {
            throw new RuntimeException("Illegal hexadecimal character " + ch + " at index " + index);
        }
        return digit;
    }

    
    /** 
     * 字符串转换为16进制字符串 
     *  
     * @param s 
     * @return 
     */  
    public static String toHex(String str) {
        return new String(encodeHex(str.getBytes()));
    }

    
    /** 
     * 16进制字符串转换为字符串 
     *  
     * @param s 
     * @return 
     */ 
    public static String fromHex(String hex) {
        return new String(decodeHex(hex.toLowerCase().toCharArray()));
    }




	public static String Bytes2HexString(byte[] b, int size) {
		String ret = "";

		for(int i = 0; i < size; ++i) {
			String hex = Integer.toHexString(b[i] & 255);
			if (hex.length() == 1) {
				hex = "0" + hex;
			}

			ret = ret + hex.toUpperCase();
		}

		return ret;
	}

	public static byte uniteBytes(byte src0, byte src1) {
		byte _b0 = Byte.decode("0x" + new String(new byte[]{src0}));
		_b0 = (byte)(_b0 << 4);
		byte _b1 = Byte.decode("0x" + new String(new byte[]{src1}));
		byte ret = (byte)(_b0 ^ _b1);
		return ret;
	}

	public static byte[] HexString2Bytes(String src) {
		int len = src.length() / 2;
		byte[] ret = new byte[len];
		byte[] tmp = src.getBytes();

		for(int i = 0; i < len; ++i) {
			ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
		}

		return ret;
	}

	public static int bytesToInt(byte[] bytes) {
		int addr = bytes[0] & 255;
		addr |= bytes[1] << 8 & '\uff00';
		addr |= bytes[2] << 16 & 16711680;
		addr |= bytes[3] << 25 & -16777216;
		return addr;
	}

	public static byte[] intToByte(int i) {
		byte[] abyte0 = new byte[]{(byte)(255 & i), (byte)(('\uff00' & i) >> 8), (byte)((16711680 & i) >> 16), (byte)((-16777216 & i) >> 24)};
		return abyte0;
	}

	/**
	 * 将16进制单精度浮点型转换为10进制浮点型
	 *
	 * @return float
	 * @since 1.0
	 */
	private static float parseHex2Float(String hexStr) {
		BigInteger bigInteger = new BigInteger(hexStr, 16);
		return Float.intBitsToFloat(bigInteger.intValue());
	}

	/**
	 * 将十进制浮点型转换为十六进制浮点型
	 *
	 * @return String
	 * @since 1.0
	 */
	private static String parseFloat2Hex(float data) {
		return Integer.toHexString(Float.floatToIntBits(data));
	}


	/**
	 * @Description:	十进制转换成二进制 ()
	 * @param decimalSource
	 * @return String
	 */
	public static String decimalToBinary(int decimalSource) {
		BigInteger bi = new BigInteger(String.valueOf(decimalSource));	//转换成BigInteger类型
		return bi.toString(2);	//参数2指定的是转化成X进制，默认10进制
	}

	/**
	 * @Description:	二进制转换成十进制
	 * @param binarySource
	 * @return int
	 */
	public static int binaryToDecimal(String binarySource) {
		BigInteger bi = new BigInteger(binarySource, 2);    //转换为BigInteger类型
		return Integer.parseInt(bi.toString());        //转换成十进制
	}

	public static void main(String[] args) {
//		String hexString = "55aa000300020105";
//		System.out.println(hexString2binaryString(hexString));
//		System.out.println(decimalToHex(255));
//		binaryToDecimal(15);
//
		System.out.println(binaryToDecimal("10000000"));
	}
}
